package com.sakuracard.stepdemo.service.impl;


import com.sakuracard.stepdemo.mapper.HomeContentMapper;
import com.sakuracard.stepdemo.model.HomeContentEntity;
import com.sakuracard.stepdemo.service.HomePageContentService;
import com.sakuracard.stepdemo.service.base.BaseServiceImpl;
import com.sakuracard.stepdemo.web.model.ListResult;
import com.sakuracard.stepdemo.web.model.SearchParams;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class HomePageContentServiceImpl
    extends BaseServiceImpl<HomeContentMapper, HomeContentEntity>
    implements HomePageContentService {

  public HomePageContentServiceImpl(HomeContentMapper homeContentMapper) {
    super(homeContentMapper);
  }

  @Override
  public ListResult<HomeContentEntity> getHomePageContentList(SearchParams params) {
    int count = this.mapper.selectCount(params);
    List<HomeContentEntity> list = this.mapper.selectList(params);
    return new ListResult<>(1, count, 1, 20, list);
  }

  @Override
  public HomeContentEntity getHomePageContent(int id) {
    return this.mapper.selectById(id);
  }

  @Override
  @Transactional
  public boolean updateHomePageContent(long id, HomeContentEntity homeContentEntity) {
    homeContentEntity.setUpdatedUser("admin");
    homeContentEntity.setUpdatedTime(LocalDateTime.now());
    homeContentEntity.setId((int) id);
    return this.mapper.update(homeContentEntity) == 1;
  }

  @Override
  @Transactional
  public boolean addHomePageContent(HomeContentEntity homeContentEntity) {
    homeContentEntity.setCreatedUser("admin");
    homeContentEntity.setUpdatedUser("admin");
    LocalDateTime now = LocalDateTime.now();
    homeContentEntity.setCreatedTime(now);
    homeContentEntity.setUpdatedTime(now);

    return this.mapper.insert(homeContentEntity) > 0;
  }

  @Override
  @Transactional
  public boolean updatePageContent(int id, String content) {
    Objects.requireNonNull(content);
    return this.mapper.updatePageContent(Map.of("id", id, "content", content)) == 1;
  }
}
